﻿using GarminConnect;

namespace GarminUtils
{
    /// <summary>
    /// 佳明国际区
    /// </summary>
    public class GarminGlobal
    {
        // 环境变量读取，带默认值
        private static readonly string GARMIN_USERNAME = Environment.GetEnvironmentVariable("GARMIN_GLOBAL_USERNAME_DEFAULT") ?? Constant.GarminGlobalUsernameDefault;
        private static readonly string GARMIN_PASSWORD = Environment.GetEnvironmentVariable("GARMIN_GLOBAL_PASSWORD_DEFAULT") ?? Constant.GarminGlobalPasswordDefault;
        private static readonly string GARMIN_MIGRATE_NUM = Environment.GetEnvironmentVariable("GARMIN_MIGRATE_NUM") ?? Constant.GarminMigrateNumDefault.ToString();
        private static readonly string GARMIN_MIGRATE_START = Environment.GetEnvironmentVariable("GARMIN_MIGRATE_START") ?? Constant.GarminMigrateStartDefault.ToString();
        private static readonly int GARMIN_SYNC_NUM = int.TryParse(Environment.GetEnvironmentVariable("GARMIN_SYNC_NUM"), out var syncNum) ? syncNum : Constant.GarminSyncNumDefault;

        /// <summary>
        /// 获取佳明国际区客户端
        /// </summary>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static async Task<GarminConnectClient> GetGarminGlobalClientAsync()
        {
            if (string.IsNullOrWhiteSpace(GARMIN_USERNAME) || string.IsNullOrWhiteSpace(GARMIN_PASSWORD))
            {
                var errMsg = "请填写国际区区用户名及密码：GARMIN_USERNAME,GARMIN_PASSWORD";
                Console.Error.WriteLine(errMsg);
                // 这里可以抛异常或者返回null，根据需求调整
                throw new ArgumentException(errMsg);
            }

            var GCClient = new GarminConnectClient(new GCCredentials
            {
                Username = GARMIN_USERNAME,
                Password = GARMIN_PASSWORD
            }, GarminDomain.GarminCom);

            try
            {
                //await SqliteHelper.InitDBAsync();

                //var currentSession = await SqliteHelper.GetSessionFromDBAsync("CN");
                //if (currentSession == null)
                //{
                //    await GCClient.LoginAsync();
                //    await SqliteHelper.SaveSessionToDBAsync("CN", GCClient.ExportToken());
                //}
                //else
                //{
                //    try
                //    {
                //        Console.WriteLine("GarminCN: login by saved session");
                //        await GCClient.LoadTokenAsync(currentSession.OAuth1, currentSession.OAuth2);
                //    }
                //    catch (Exception)
                //    {
                //        Console.WriteLine("Warn: renew GarminCN Session..");
                //        await GCClient.LoginAsync(GARMIN_USERNAME, GARMIN_PASSWORD);
                //        await SqliteHelper.UpdateSessionToDBAsync("CN", GCClient.SessionJson);
                //    }
                //}

                await GCClient.LoginAsync();

                var userInfo = await GCClient.GetUserProfileAsync();
                var fullName = userInfo.FullName;
                var emailAddress = userInfo.UserName;
                var location = userInfo.Location;

                if (string.IsNullOrEmpty(fullName))
                {
                    throw new Exception("佳明国际区登录失败");
                }

                Console.WriteLine($"Garmin userInfo Global: fullName={fullName}, emailAddress={emailAddress}, location={location}");

                return GCClient;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                // 这里可以根据需要抛异常或者返回null
                throw;
            }
        }
    }


    public class UserProfile
    {
        public string FullName { get; set; }
        public string UserName { get; set; } // 邮箱
        public string Location { get; set; }
    }


    // 你需要实现的数据库操作接口
    public static class DatabaseHelper
    {
        public static Task InitDBAsync()
        {
            // 初始化数据库
            return Task.CompletedTask;
        }

        public static Task<Session> GetSessionFromDBAsync(string key)
        {
            // 从数据库获取 session
            return Task.FromResult<Session>(null);
        }

        public static Task SaveSessionToDBAsync(string key, Session session)
        {
            // 保存 session
            return Task.CompletedTask;
        }

        public static Task UpdateSessionToDBAsync(string key, Session session)
        {
            // 更新 session
            return Task.CompletedTask;
        }
    }

    public class Session
    {
        public Oauth1Token Oauth1 { get; set; }
        public Oauth2Token Oauth2 { get; set; }
        public string SessionJson { get; set; }
    }

    // 数字转大写（示例实现）
    public static class NumberTricks
    {
        private static readonly string[] Capitals = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
        public static string Number2Capital(int num)
        {
            if (num < 0) return "";
            if (num < Capitals.Length) return Capitals[num];
            return num.ToString();
        }
    }

    // 这里是核心逻辑实现
    public static class GarminService
    {
        private static readonly string GARMIN_GLOBAL_USERNAME = Environment.GetEnvironmentVariable("GARMIN_GLOBAL_USERNAME") ?? Constant.GarminGlobalUsernameDefault;
        private static readonly string GARMIN_GLOBAL_PASSWORD = Environment.GetEnvironmentVariable("GARMIN_GLOBAL_PASSWORD") ?? Constant.GarminGlobalPasswordDefault;
        private static readonly int GARMIN_MIGRATE_NUM = int.TryParse(Environment.GetEnvironmentVariable("GARMIN_MIGRATE_NUM"), out var migrateNum) ? migrateNum : Constant.GarminMigrateNumDefault;
        private static readonly int GARMIN_MIGRATE_START = int.TryParse(Environment.GetEnvironmentVariable("GARMIN_MIGRATE_START"), out var migrateStart) ? migrateStart : Constant.GarminMigrateStartDefault;
        private static readonly int GARMIN_SYNC_NUM = int.TryParse(Environment.GetEnvironmentVariable("GARMIN_SYNC_NUM"), out var syncNum) ? syncNum : Constant.GarminSyncNumDefault;

        // 你需要实现或注入的 GarminConnect 类
        private static GarminConnectClient CreateGarminConnectClient(string username, string password)
        {
            return new GarminConnectClient(new GCCredentials
            {
                Username = username,
                Password = password
            }, GarminDomain.GarminCom);
        }

        // 获取国际区客户端
        public static async Task<GarminConnectClient> GetGaminGlobalClientAsync()
        {
            if (string.IsNullOrWhiteSpace(GARMIN_GLOBAL_USERNAME) || string.IsNullOrWhiteSpace(GARMIN_GLOBAL_PASSWORD))
            {
                var errMsg = "请填写国际区用户名及密码：GARMIN_GLOBAL_USERNAME,GARMIN_GLOBAL_PASSWORD";
                Console.Error.WriteLine(errMsg);
                throw new Exception(errMsg);
            }

            var gcClient = CreateGarminConnectClient(GARMIN_GLOBAL_USERNAME, GARMIN_GLOBAL_PASSWORD);

            try
            {
                await DatabaseHelper.InitDBAsync();

                var currentSession = await DatabaseHelper.GetSessionFromDBAsync("GLOBAL");
                if (currentSession == null)
                {
                    await gcClient.LoginAsync();
                    var token = gcClient.ExportToken();
                    await DatabaseHelper.SaveSessionToDBAsync("GLOBAL", new Session { SessionJson = token.ToString() });
                }
                else
                {
                    try
                    {
                        Console.WriteLine("GarminGlobal: login by saved session");
                        gcClient.LoadToken(currentSession.Oauth1, currentSession.Oauth2);
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("Warn: renew GarminGlobal session..");
                        await gcClient.LoginAsync();
                        var sessionJson = gcClient.ExportToken();
                        await DatabaseHelper.UpdateSessionToDBAsync("GLOBAL", new Session { SessionJson = sessionJson.ToString() });
                    }
                }

                var userInfo = await gcClient.GetUserProfileAsync();
                if (string.IsNullOrEmpty(userInfo.UserName))
                {
                    throw new Exception("佳明国际区登录失败，请检查填入的账号密码或您的网络环境");
                }

                Console.WriteLine($"Garmin userInfo global: FullName={userInfo.FullName}, Email={userInfo.UserName}, Location={userInfo.Location}");
                return gcClient;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
                throw;
            }
        }
    }
}
